//
//  DYSimilarBigPicView.m
//  PrivatePhoto
//
//  Created by PrivatePhoto Team on 2021.
//  Copyright © 2021年 PrivatePhoto Team. All rights reserved.
//

#import "DYSimilarBigPicView.h"
#import "VLocalImageCache.h"
#import "FPPhotosTool.h"
#import <ReactiveObjC.h>
#import "DYSimilarPicItemCell.h"
#import "DYSimilarPicCellModel.h"



@interface CASimilarPicBigView : UIView
@property (nonatomic, strong) UIImageView *bigView;
@property (nonatomic, strong) UIButton *selectButton;
@property (nonatomic, strong) UIButton *bottomLeftBtn;
@property (nonatomic, strong) UILabel *bottomRightLabel;
@property (nonatomic, strong) DYSimilarPicModel *photoItem;
@property (nonatomic, strong) NSMutableArray *selectedArray;
@property (nonatomic, copy) void (^seletedBigImgBlock)(DYSimilarPicModel *info,BOOL isAdd,NSMutableArray *array);
@property (nonatomic, copy) void (^showDetailImageBlock) (DYSimilarPicModel *model);
@end

@implementation CASimilarPicBigView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        [self configSubViews];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    CGFloat photoItemHeight = (kScreenWidth-4)/2;
    [self.bigView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.top.mas_offset(0);
//        make.right.mas_offset(-1);
        make.width.height.mas_equalTo(photoItemHeight);
    }];
    [self.selectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-8);
        make.top.mas_offset(8);
    }];
    [self.bottomLeftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(8);
        make.bottom.mas_offset(-8);
        make.width.height.mas_equalTo(25);
    }];
    [self.bottomRightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-8);
        make.bottom.mas_offset(-8);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(25);
    }];

}

- (void)configSubViews{
    
    [self addSubview:self.bigView];
    
    [self addSubview:self.selectButton];
    [self bringSubviewToFront:self.selectButton];
    
    [self addSubview:self.bottomLeftBtn];
    [self bringSubviewToFront:self.bottomLeftBtn];
   
    [self addSubview:self.bottomRightLabel];
    [self bringSubviewToFront:self.bottomRightLabel];
}

- (void)showPhotoWithAsset:(PHAsset *)asset{
    UIImage *image =  [[VLocalImageCache shareCache].cache objectForKey:asset.localIdentifier];
    
    if (image) {
        self.bigView.image = image;
    }else{
        @weakify(self)
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            PHCachingImageManager *imageManager = [FPPhotosTool shareFPPhotosTool].cacheImageManager;
//             [imageManager requestImageForAsset:asset targetSize:[FPPhotosTool shareFPPhotosTool].coverImageSize contentMode:PHImageContentModeAspectFill options:[FPPhotosTool shareFPPhotosTool].coverImageOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//                 @strongify(self)
//                 if (result) return;
//                 dispatch_sync(dispatch_get_main_queue(), ^{
//                     self.bigView.image = result;
//                     [[VLocalImageCache shareCache].cache setObject:result forKey:asset.localIdentifier];
//                });
//             }];
//        });
        
        
       PHCachingImageManager *imageManager = [FPPhotosTool shareFPPhotosTool].cacheImageManager;
        [imageManager requestImageForAsset:asset targetSize:[FPPhotosTool shareFPPhotosTool].coverImageSize contentMode:PHImageContentModeAspectFill options:[FPPhotosTool shareFPPhotosTool].coverImageOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            @strongify(self)
            if (result) {
                self.bigView.image = result;
                [[VLocalImageCache shareCache].cache setObject:result forKey:asset.localIdentifier];
            }
        }];
    }
}

- (void)selectedImageComplete:(UIButton *)sender{
    sender.selected = !sender.selected;
    BOOL isAdd = sender.selected;
//    if ([self.selectedArray containsObject:self.photoItem]) {
//        [self.selectedArray removeObject:self.photoItem];
//        self.layer.mask = nil;
//        isAdd = NO;
//    }else{
//        [self.selectedArray addObject:self.photoItem];
//        CALayer *layer = [[CALayer alloc] init];
//        layer.frame = self.bounds;
//        layer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7].CGColor;
//        self.layer.mask = layer;
//        isAdd = YES;
//    }
    !self.seletedBigImgBlock ?:self.seletedBigImgBlock(self.photoItem,isAdd,self.selectedArray);
}

- (void)imgViewDidClick{
    !self.showDetailImageBlock ?: self.showDetailImageBlock(self.photoItem);
}

#pragma mark --setter/getter

- (void)setPhotoItem:(DYSimilarPicModel *)photoItem{
    _photoItem = photoItem;
    [self showPhotoWithAsset:photoItem.asset];
}

- (void)setSelectedArray:(NSMutableArray *)selectedArray{
    _selectedArray = selectedArray;
    for (DYSimilarPicModel *sel in selectedArray) {
        if (sel.space == self.photoItem.space) {
            self.selectButton.selected = YES;
            CALayer *layer = [[CALayer alloc] init];
            layer.frame = self.bounds;
            layer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7].CGColor;
            self.layer.mask = layer;
        }else{
            self.selectButton.selected = NO;
            self.layer.mask = nil;
        }
    }
//    if ([selectedArray containsObject:self.photoItem]) {
//        self.selectButton.selected = YES;
//        CALayer *layer = [[CALayer alloc] init];
//        layer.frame = self.bounds;
//        layer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7].CGColor;
//        self.layer.mask = layer;
//    }else{
//        self.selectButton.selected = NO;
//        self.layer.mask = nil;
//
//    }
}

- (UIImageView *)bigView{
    if (!_bigView) {
        _bigView = [[UIImageView alloc] init];
        _bigView.userInteractionEnabled = YES;
//        _bigView.contentMode = UIViewContentModeScaleAspectFit;
        _bigView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _bigView.layer.borderWidth = 0.5f;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgViewDidClick)];
        [_bigView addGestureRecognizer:tap];
    }
    return _bigView;
}

- (UIButton *)selectButton {
    if (!_selectButton) {
        _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectButton.titleLabel.font = [UIFont systemFontOfSize:14.f];
        _selectButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_selectButton setImage:[UIImage imageNamed:@"bk"] forState:UIControlStateNormal];
        [_selectButton setImage:[UIImage imageNamed:@"xz"] forState:UIControlStateSelected];
        [_selectButton addTarget:self action:@selector(selectedImageComplete:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectButton;
}

- (UIButton *)bottomLeftBtn {
    if (!_bottomLeftBtn) {
        _bottomLeftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _bottomLeftBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
        [_bottomLeftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _bottomLeftBtn.backgroundColor = [UIColor clearColor];
        _bottomLeftBtn.layer.cornerRadius = 25/2;
        _bottomLeftBtn.layer.masksToBounds = YES;
//        [_bottomLeftBtn addTarget:self action:@selector(selectedImageComplete:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomLeftBtn;
}

- (UILabel *)bottomRightLabel{
    if (!_bottomRightLabel) {
        _bottomRightLabel = [[UILabel alloc] init];
        _bottomRightLabel.font = [UIFont systemFontOfSize:15];
        _bottomRightLabel.textColor = [UIColor blackColor];
        _bottomRightLabel.backgroundColor = [UIColor whiteColor];
        _bottomRightLabel.textAlignment = NSTextAlignmentCenter;
        _bottomRightLabel.text = @"最佳照片";
        self.bottomRightLabel.layer.cornerRadius = 25/2;
        self.bottomRightLabel.layer.masksToBounds = YES;
    }
    return _bottomRightLabel;
}

@end


@interface DYSimilarBigPicView ()<UICollectionViewDelegate, UICollectionViewDataSource>
{
    CGFloat _margin;
    CGFloat col;
}
@property (nonatomic, strong) CASimilarPicBigView *bigImageView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray *assetArray;
@end

@implementation DYSimilarBigPicView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        [self configSubView];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.bigImageView.frame = CGRectMake(0, 0, self.width/2, self.height);
    self.collectionView.frame = CGRectMake(CGRectGetMaxX(self.bigImageView.frame), 0, self.width/2, self.height);
}

- (void)configSubView{
    
    [self addSubview:self.bigImageView];
    [self addSubview:self.collectionView];
}

- (void)handleCellForSelectedButtonNumberShowEvent:(NSIndexPath *)currentIndexPath
{
    BOOL isAdd = NO;
    NSInteger index = currentIndexPath.item;
    DYSimilarPicModel *model = self.imgArray[index];
    if ([self.seletedArray containsObject:model]) {
        [self.seletedArray removeObject:model];
        isAdd = NO;
    }else{
        [self.seletedArray addObject:model];
        isAdd = YES;
    }
    [self.collectionView reloadData];
    !self.SimilarBigPicViewBlock ?:self.SimilarBigPicViewBlock(model,isAdd,self.seletedArray);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    DYSimilarPicModel *model = self.imgArray[indexPath.item];
    if ([self.assetArray containsObject:self.bigImgItem.asset]) {
        !self.lookDetailBlock ?: self.lookDetailBlock(model, indexPath.item+1,self.assetArray);
    }else{
        
        !self.lookDetailBlock ?: self.lookDetailBlock(model, indexPath.item,self.assetArray);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    return CGSizeMake((self.collectionView.width-2)/2, (self.collectionView.height-2)/2);
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imgArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   
      DYSimilarPicItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DYSimilarPicItemCell" forIndexPath:indexPath];
      DYSimilarPicModel *model = self.imgArray[indexPath.item];
      [cell updateViewWithModel:model selectedArray:self.seletedArray];
        __weak typeof(self) weakSelf = self;
      cell.selectPhotoCompleteBlock = ^{
            [weakSelf handleCellForSelectedButtonNumberShowEvent:indexPath];
      };
      return cell;
    
}

#pragma mark --- setter/getter

- (void)setBigImgItem:(DYSimilarPicModel *)bigImgItem{
    _bigImgItem = bigImgItem;
    self.bigImageView.photoItem = bigImgItem;
    [self.assetArray insertObject:bigImgItem.asset atIndex:0];
}

- (void)setImgArray:(NSArray *)imgArray{
    _imgArray = imgArray;
    if (self.assetArray.count) {
        [self.assetArray removeObjectsInArray:imgArray];
    }
    @weakify(self)
    [imgArray enumerateObjectsUsingBlock:^(DYSimilarPicModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       @strongify(self)
        [self.assetArray addObject:obj.asset];
    }];
    [self.collectionView reloadData];
}

- (void)setSeletedArray:(NSMutableArray *)seletedArray{
    _seletedArray = seletedArray;
    self.bigImageView.selectedArray = seletedArray;
}

- (CASimilarPicBigView *)bigImageView{
    if (!_bigImageView) {
        _bigImageView = [[CASimilarPicBigView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth/2, self.height)];
       @weakify(self)
        _bigImageView.showDetailImageBlock = ^(DYSimilarPicModel *model) {
            @strongify(self)
//            [FPPhotosTool browserImagesWithAssetArray:self.assetArray index:0];
            !self.lookDetailBlock ?: self.lookDetailBlock(model,0,self.assetArray);
        };
        
        _bigImageView.seletedBigImgBlock = ^(DYSimilarPicModel *info, BOOL isAdd, NSMutableArray *array) {
            @strongify(self)
            if ([self.seletedArray containsObject:info]) {
                if (isAdd) {return;}
                [self.seletedArray removeObject:info];
            }else{
                if (!isAdd) {return;}
                [self.seletedArray addObject:info];
            }
//            self.seletedArray = array;
            !self.SimilarBigPicViewBlock ?:self.SimilarBigPicViewBlock(info,isAdd,self.seletedArray);
        };
    }
    return _bigImageView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.allowsMultipleSelection = YES;
        _collectionView.bounces = YES;
        _collectionView.scrollEnabled = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[DYSimilarPicItemCell class] forCellWithReuseIdentifier:@"DYSimilarPicItemCell"];
       
    }
    return _collectionView;
}
- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.itemSize = CGSizeMake(75, 75);
        [_flowLayout setSectionInset:UIEdgeInsetsMake(0, _margin, 0, _margin)];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowLayout.minimumLineSpacing = _margin;
        _flowLayout.minimumInteritemSpacing = _margin;
    }
    return _flowLayout;
}

- (NSMutableArray *)assetArray{
    if (!_assetArray) {
        _assetArray = [[NSMutableArray alloc] init];
    }
    return _assetArray;
}

@end
